<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属年份" prop="years">
        <el-input
          v-model="queryParams.years"
          placeholder="请输入所属年份"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所属月份">
        <el-row :gutter="10">
          <el-col :span="11">
            <el-input
              v-model="queryParams.monthMin"
              placeholder="最小值"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-col>
          <el-col :span="11">
            <el-input
              v-model="queryParams.monthMax"
              placeholder="最大值"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="项目名称" prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="请输入项目名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单价">
        <el-row :gutter="10">
          <el-col :span="11">
            <el-input
              v-model="queryParams.unitPriceMin"
              placeholder="最小值"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-col>
          <el-col :span="11">
            <el-input
              v-model="queryParams.unitPriceMax"
              placeholder="最大值"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="总金额">
        <el-row :gutter="10">
          <el-col :span="11">
            <el-input
              v-model="queryParams.totalAmountMin"
              placeholder="最小值"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-col>
          <el-col :span="11">
            <el-input
              v-model="queryParams.totalAmountMax"
              placeholder="最大值"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="是否启用" prop="isActive">
        <el-select v-model="queryParams.isActive" placeholder="请选择是否启用" clearable>
          <el-option
            v-for="dict in dict.type.admin_is_active"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['accounting:xiaoyuan:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['accounting:xiaoyuan:edit']"
        >修改</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plainhandleDelete
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['accounting:xiaoyuan:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['accounting:xiaoyuan:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete-solid"
          size="mini"
          @click="handleTimeRemove"
          v-hasPermi="['accounting:xiaoyuan:remove']"
        >清除报账日期</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="xiaoyuanList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键ID" align="center" prop="id" />
      <el-table-column label="所属年份" align="center" prop="years" />
      <el-table-column label="所属月份" align="center" prop="month" />
      <el-table-column label="报销日期" align="center" prop="accountingTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.accountingTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目名称" align="center" prop="projectName" />
      <el-table-column label="单价" align="center" prop="unitPrice" />
      <el-table-column label="数量" align="center" prop="quantity" />
      <el-table-column label="总金额" align="center" prop="totalAmount" />
      <el-table-column label="小计" align="center" prop="subtotal" />
      <el-table-column label="单据凭证" align="center" prop="documentVoucher" width="180">
        <template slot-scope="scope">
          <div v-if="scope.row.documentVoucher">
            <image-preview
              v-for="(img, index) in scope.row.documentVoucher.split(',')"
              :key="index"
              :src="img"
              :width="50"
              :height="50"
              style="margin-right: 5px;"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="是否启用" align="center" prop="isActive">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.admin_is_active" :value="scope.row.isActive"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['accounting:xiaoyuan:edit']"
          >修改</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['accounting:xiaoyuan:remove']"
          >删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 时间选择对话框 -->
    <el-dialog title="选择账单时间" :visible.sync="timeDialogVisible" width="400px" append-to-body>
      <el-form :model="timeForm" ref="timeForm" label-width="80px">
        <el-form-item label="选择日期" prop="billDate">
          <el-date-picker
            v-model="timeForm.billDate"
            type="month"
            value-format="yyyy-MM"
            placeholder="选择年月"
            style="width: 100%;"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="timeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleTimeSave">确定</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改后台-小院报销对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="报销日期" prop="accountingTime">
          <el-date-picker clearable
                          v-model="form.accountingTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择报销日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-input v-model="form.projectName" placeholder="请输入项目名称" />
        </el-form-item>
        <el-form-item label="单价" prop="unitPrice">
          <el-input v-model="form.unitPrice" placeholder="请输入单价" @input="calculateAmounts" @change="calculateAmounts" />
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input v-model="form.quantity" placeholder="请输入数量" @input="calculateAmounts" @change="calculateAmounts" />
        </el-form-item>
        <el-form-item label="总金额" prop="totalAmount">
          <el-input v-model="form.totalAmount" placeholder="请输入总金额" />
        </el-form-item>
        <el-form-item label="小计" prop="subtotal">
          <el-input v-model="form.subtotal" placeholder="请输入小计" />
        </el-form-item>
        <el-form-item label="单据凭证" prop="documentVoucher">
          <image-upload v-model="form.documentVoucher" multiple/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="是否启用" prop="isActive">
          <el-select v-model="form.isActive" placeholder="请选择是否启用">
            <el-option
              v-for="dict in dict.type.admin_is_active"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listXiaoyuan, getXiaoyuan, delXiaoyuan, addXiaoyuan, updateXiaoyuan, getTime, timeSave, timeremove } from "@/api/accounting/xiaoyuan"

export default {
  name: "Xiaoyuan",
  dicts: ['admin_is_active'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 后台-小院报销表格数据
      xiaoyuanList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        years: null,
        monthMin: null,
        monthMax: null,
        projectName: null,
        unitPriceMin: null,
        unitPriceMax: null,
        totalAmountMin: null,
        totalAmountMax: null,
        isActive: null,
      },
      // 表单参数
      form: {},
      // 时间选择对话框
      timeDialogVisible: false,
      // 时间选择表单
      timeForm: {
        billDate: null,
        years: null,
        month: null
      },
      // 表单校验
      rules: {
        month: [
          { required: true, message: "所属月份不能为空", trigger: "blur" }
        ],
        accountingTime: [
          { required: true, message: "报销日期不能为空", trigger: "blur" }
        ],
        projectName: [
          { required: true, message: "项目名称不能为空", trigger: "blur" }
        ],
        unitPrice: [
          { required: true, message: "单价不能为空", trigger: "blur" }
        ],
        quantity: [
          { required: true, message: "数量不能为空", trigger: "blur" }
        ],
        totalAmount: [
          { required: true, message: "总金额不能为空", trigger: "blur" }
        ],
        subtotal: [
          { required: true, message: "小计不能为空", trigger: "blur" }
        ],
        documentVoucher: [
          { required: true, message: "单据凭证不能为空", trigger: "blur" }
        ],
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询后台-小院报销列表 */
    getList() {
      this.loading = true
      listXiaoyuan(this.queryParams).then(response => {
        this.xiaoyuanList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        years: null,
        month: null,
        accountingTime: null,
        projectName: null,
        unitPrice: null,
        quantity: null,
        totalAmount: null,
        subtotal: null,
        documentVoucher: null,
        remark: null,
        createdAt: null,
        createdBy: null,
        updatedAt: null,
        updatedBy: null,
        isActive: null,
        isDeleted: null,
        deletedAt: null,
        tenantId: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 1. 先清空所有查询参数为初始值
      const initialQueryParams = {
        pageNum: 1,
        pageSize: 10,
        years: '',  // 使用空字符串而不是null，更符合输入框的空状态
        monthMin: '',
        monthMax: '',
        projectName: '',
        unitPriceMin: '',
        unitPriceMax: '',
        totalAmountMin: '',
        totalAmountMax: '',
        isActive: null
      }
      
      // 2. 使用Vue.set逐个更新，确保响应式系统能检测到变化
      Object.keys(initialQueryParams).forEach(key => {
        this.$set(this.queryParams, key, initialQueryParams[key])
      })
      
      // 3. 如果表单引用存在，手动清空每个输入框的值
      if (this.$refs.queryForm && this.$refs.queryForm.fields) {
        this.$refs.queryForm.fields.forEach(field => {
          field.value = ''
          field.resetField()
        })
      }
      
      // 4. 使用$forceUpdate强制重新渲染组件
      this.$forceUpdate()
      
      // 5. 在nextTick中执行查询，确保所有更新都已完成
      this.$nextTick(() => {
        this.handleQuery()
      })
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      // 先调用getTime接口检查数据
      getTime().then(response => {
        if (response.data && response.data !== null) {
          // 数据不为空，直接打开新增框
          this.reset()
          this.open = true
          this.title = "添加后台-小院报销"
        } else {
          // 数据为空，打开时间选择对话框
          this.timeForm.billDate = null
          this.timeDialogVisible = true
        }
      }).catch(error => {
        this.$modal.msgError('获取时间信息失败，请重试')
      })
    },
    
    /** 时间选择确认操作 */
    handleTimeSave() {
      if (!this.timeForm.billDate) {
        this.$modal.msgError('请选择日期')
        return
      }
      
      // 分割年月
      const dateParts = this.timeForm.billDate.split('-')
      const years = parseInt(dateParts[0])
      const month = parseInt(dateParts[1])
      
      // 构造请求参数
      const params = {
        years: years,
        month: month
      }
      
      // 调用timeSave接口
      timeSave(params).then(response => {
        this.$modal.msgSuccess('时间保存成功')
        this.timeDialogVisible = false
        // 打开正常的新增框
        this.reset()
        this.open = true
        this.title = "添加后台-小院报销"
      }).catch(error => {
        this.$modal.msgError('时间保存失败，请重试')
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getXiaoyuan(id).then(response => {
        // 处理逗号分隔的单据凭证URL，转换为数组以便上传组件正确显示
        if (response.data.documentVoucher && typeof response.data.documentVoucher === 'string') {
          response.data.documentVoucher = response.data.documentVoucher.split(',')
        }
        this.form = response.data
        this.open = true
        this.title = "修改后台-小院报销"
      })
    },
    /** 计算总金额和小计 */
    calculateAmounts() {
      const unitPrice = parseFloat(this.form.unitPrice) || 0
      const quantity = parseFloat(this.form.quantity) || 0
      if (unitPrice > 0 && quantity > 0) {
        const amount = unitPrice * quantity
        this.form.totalAmount = amount.toFixed(2)
        this.form.subtotal = amount.toFixed(2)
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理多张单据凭证，将数组转换为逗号分隔的字符串
          if (Array.isArray(this.form.documentVoucher)) {
            this.form.documentVoucher = this.form.documentVoucher.join(',')
          }
          
          if (this.form.id != null) {
            updateXiaoyuan(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addXiaoyuan(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除后台-小院报销编号为"' + ids + '"的数据项？').then(function() {
        return delXiaoyuan(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('accounting/xiaoyuan/export', {
        ...this.queryParams
      }, `xiaoyuan_${new Date().getTime()}.xlsx`)
    },
    /** 清除报账日期按钮操作 */
    handleTimeRemove() {
      this.$modal.confirm('是否确认清除所有报账日期数据？').then(function() {
        return timeremove()
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("清除报账日期成功")
      }).catch(() => {})
    }
  }
}
</script>
